﻿using System;
using System.Collections.Generic;
using System.Data.SQLite;
//using System.Data.SQLite;
using System.Data;
using System.Threading;
using System.Text;

namespace DATA_SERVER
{
    class Data_Thread
    {
        public class Record
        {
            public string staffno;
            public string time;
            public string strSN;
        }
        public static Queue<Record> RecordList = new Queue<Record>();           //待存储门禁记录队列
        public static EventWaitHandle NewRec = new AutoResetEvent(false);
        public readonly static object _Reclocker = new object();

        //将门禁记录加入保存队列
        public static void SaveRecord(string staffno, string time, string strSN)
        {
            Record rec = new Record();
            rec.staffno = staffno;
            rec.time = time;
            rec.strSN = strSN;
            lock (_Reclocker)
            {
                RecordList.Enqueue(rec);
            }
            NewRec.Set();
        }

        //存储线程函数
        public static void WriteToDB()
        {
            while (true)
            {
                Record rec = null;
                lock (_Reclocker)
                {
                    if (RecordList.Count > 0)
                    {
                        rec = RecordList.Dequeue();         //从队列中取出记录
                        if (rec == null)
                        {
                            return;
                        }
                    }
                }
                if (rec != null)
                {
                    try
                    {
                        //将记录写入远程数据库

                        string spl = string.Format("INSERT INTO [T_PP_AccessControl] ([StaffNo],[Time],[BeaMac]) VALUES('{0}','{1}','{2}')", rec.staffno, rec.time, rec.strSN);
                        DB_SQLServer.ExecuteNonQuery(string.Format("INSERT INTO [T_PP_AccessControl] ([StaffNo],[Time],[BeaMac]) VALUES('{0}','{1}','{2}')", rec.staffno, rec.time, rec.strSN));
                    }
                    catch
                    {
                        try
                        {
                            //写入远程数据库失败则将记录写入本地数据库
                            DB_SQLite.ExecuteNonQuery(string.Format("INSERT INTO [T_PP_AccessControl] ([StaffNo],[Time],[BeaMac]) VALUES('{0}',DATETIME('{1}'),'{2}')", rec.staffno, rec.time, rec.strSN));
                        }
                        catch { }
                    }

                }
                else
                {
                    NewRec.WaitOne();
                }
            }
        }

        public static void StartThread()
        {
            Thread save_Thread = new Thread(new ThreadStart(WriteToDB));
            save_Thread.IsBackground = true;
            save_Thread.Start();
        }

        public static void EndThread()
        {
            RecordList.Enqueue(null);
            NewRec.Set();
        }
    }
}
